<template>
  <div  class="history-local" v-if="!search">
    <ul>
      <li v-for="(item,index) in historyList"
          :key="index" @click="searchSend(item)">
        <div class="searchlist-title">
          {{item.name}}
        </div>
        <div class="searchlist-address">
          {{item.address}}
        </div>
      </li>
      <button @click='empty' v-if="historyList.length > 0 ">清空所有</button>
    </ul>
  </div>
</template>

<script>
export default {
  data () {
    return {
      historyList:[],
    }
  },
  props:['value','search'],
  created() {
    this.getLocalKey();
  },
  watch:{
    'value':function(newV){
      this.setLocalHistory(newV);
    },
  },
  methods: {
    setLocalHistory (value) {
      /** 先判断*/
      this.getLocalKey(value)
      /** 搜索历史*/
      // 没有搜索记录，把搜索值push进数组首位，存入本地
      if (!this.historyList.includes(value)) {
        this.historyList.unshift(value);
        localStorage.setItem("historyList", JSON.stringify(this.historyList));
      } else {
        //有搜索记录，删除之前的旧记录，将新搜索值重新push到数组首位
        let i = this.historyList.indexOf(value);
        this.historyList.splice(i, 1)
        this.historyList.unshift(value);
        localStorage.setItem("historyList", JSON.stringify(this.historyList));
      }
      console.log(this.historyList)
      this.$forceUpdate()
      
    },
    /** 判断 localStorage中 是否有 historyList*/
    getLocalKey () {
      //如果本地存储的数据historyList有值，直接赋值给data中的historyList
      if (JSON.parse(localStorage.getItem("historyList"))) {
        this.historyList = JSON.parse(localStorage.getItem("historyList"));
      } else {
        this.historyList = []
      }
    },
    /** 清空历史搜索记录 */
    empty () {
      localStorage.removeItem('historyList');
      this.historyList = [];
    },
    searchSend(item){
      console.log(item)
    },
  },
}
</script>

<style lang="less">
.history-local{
  ul{
    display: flex;
    flex-direction: column;
    background-color: #fff;
    li{
      height: 73.33px;
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      box-sizing: border-box;
      padding: 0 10px;
      border-bottom: 1px solid #e3e3e3;
      .searchlist-title{
        color: #333;
        font-size: 15px;
      }
      .searchlist-address{
        color: #999;
        font-size: 12px;
      }
    }
    button{
      width: 100%;
      height: 46px;
      background-color: #fff;
      line-height: 46px;
      text-align: center;
      outline: none;
      border: none;
      border-bottom: 1px solid #e3e3e3;
      color: #666;
      font-size: 16px;
    }
  }
}
</style>